import 'package:cache_store/src/helpers/serialization.dart';

import 'serializer.dart';

class CacheListSerializer<T> extends CacheSerializer<List<T>> {
  final CacheSerializer<T> childSerializer;

  CacheListSerializer(this.childSerializer);

  @override
  Deserialized<List<T>> deserialize(List<int> data) {
    final result = <T>[];

    var i = 0;
    while (i < data.length) {
      final item = childSerializer.deserialize(data.skip(i).toList());
      i += item.readBytes;
      result.add(item.value);
    }

    return Deserialized(result, i);
  }

  @override
  List<int> serialize(List<T> value) {
    return value.expand((x) => childSerializer.serialize(x)).toList();
  }
}
